<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\Work;
use app\model\BalanceWarningConfig;
use think\Request;

class BalanceWarning extends Controller
{
    /**
     * @api {POST} /admin/balanceWarning/getConfig 余额预警配置获取
     * @apiDescription 余额预警配置获取
     * @apiName  balanceWarningConfigSGet 余额预警配置获取
     * @apiGroup Admin2_0
     * @apiParam {Number=1,2} type 1 供应商 2 代理商
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function getConfig(Request $request)
    {
        if (!$type = $request->param('type')) {
            return fail('缺少必要参数');
        }
        $model = BalanceWarningConfig::where('type', $type)->find();
        if ($model) {
            $ids=explode(',', $model->user_ids);
            $model->user_ids = empty($model->user_ids)?[]:$ids;
            $model = $model->toArray();
        } else {
            $model = [];
            $model['user_ids']=[];
        }
        $work=new Work();
        $model['userList']=$work->showDepartmentUsers();
        return success('', $model);
    }

    /**
     * @api {GET} /admin/balanceWarning/saveConfig 余额预警保存
     * @apiDescription 余额预警保存
     * @apiName  balanceWarningConfigSave 余额预警保存
     * @apiGroup Admin2_0
     * @apiParam {Number=1,2} type 1 供应商 2 代理商
     * @apiParam {Number=0,1} state 开启状态 0 关闭 1 开启
     * @apiParam {String} [mobile] 手机号 type=1必填
     * @apiParam {Number} value 预警值
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function saveConfig(Request $request)
    {
        $rules = [
            'type' => 'require|integer|in:1,2',
            'state' => 'require|integer|in:0,1',
            'value' => 'require|float',
        ];
        $messages = [
            'require' => '请填写必填数据',
            'integer' => '请输入数字格式',
            'in' => '非法取值范围',
        ];
        $param = $request->only(['type', 'state', 'value']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        if ('1' == $param['type']) {
                $param['user_ids'] = $request->param('user_ids');
                $param['user_ids'] = implode(',', $param['user_ids']);
        }
        $model = BalanceWarningConfig::where('type', $param['type'])->find();
        if (!$model) {
            $model = new BalanceWarningConfig();
        }
        if (!$model->save($param)) {
            return fail('操作失败，请重试或者联系我们');
        }
        return success();
    }
}
